<?php
namespace MLM\Controller;

use Zend\View\Model\ViewModel;
use Zend\Authentication\Result;
use Zend\Authentication\AuthenticationService;

class AgentController extends \MLM\Model\Generic\Controller {

     public function indexAction() {
            $identity = $this->hasSession();
            $this->layout('layout/member');
            $view = new ViewModel();
            //Get Messages Notif
            $this->getMsgNotif($identity->member_type_id, $identity->member_id);
            return $view;
     }

     public function buysnAction() {
            $identity = $this->hasSession();
            $this->layout('layout/member');
            $view = new ViewModel();

            $script = $this->getServiceLocator()->get('viewhelpermanager')
                            ->get('inlineScript');
                    $script->appendScript("
                       jQuery(function($) {

                    $('[data-rel=tooltip]').tooltip();

                    $('.select').css('width','150px').select2({allowClear:true})
                    .on('change', function(){
                            $(this).closest('form').validate().element($(this));
                    });


                    var validation = false;
                    $('#fuelux-wizard').ace_wizard().on('change' , function(e, info){
                            if(info.step == 1 && validation) {
                                    if(!$('#validation-form').valid()) return false;
                            }
                            if(info.step == 2) {
                                return konfirmasiPembelian();
                            }
                    }).on('finished', function(e) {
                            $('#inputForm').submit();
                            $('#btnFinish').attr('disabled','disabled');

                            /*
                            bootbox.dialog('Thank you! Your information was successfully saved!', [{
                                    'label' : 'OK',
                                    'class' : 'btn-small btn-primary',
                                    }]
                            );
                            */
                    }).on('stepclick', function(e, info){

                            //return false;//prevent clicking on steps

                    });


                    $('#accordion-style').on('click', function(ev){
                            var target = $('input', ev.target);
                            var which = parseInt(target.val());
                            if(which == 2) $('#accordion').addClass('accordion-style2');
                             else $('#accordion').removeClass('accordion-style2');
                    });
                    //documentation : http://docs.jquery.com/Plugins/Validation/validate


             });

            $('#qty').ace_spinner({value:10,min:1,max:9999999,step:10, btn_up_class:'btn-info' , btn_down_class:'btn-info'})
                .on('change', function(){
                        //alert(this.value)
                        setTotalHarga(this.value);
                });
                    ");

            $request = $this->getRequest();

            $db = $this->_db;
            $conn = $db->getDriver()->getConnection();

            if ($request->isPost()) {
                $conn->beginTransaction();
                $post = $request->getPost();

                $memberId = $identity->member_id;
                $qty   = $post['qty'];
                $price = $post['price'];
                $totalPrice = $post['totalPrice'];
                $caraBayar   = $post['rdPembayaran'];

                $transStorage = new \MLM\Model\Transaction\Storage($db);
                $trans = $transStorage->buySN($memberId, $identity->member_code, 'Q000001', $price, $qty, $totalPrice, $caraBayar);
                while($trans->next()){
                        $res = $trans->current();
                        $msg = $res["out_msg"];
                        $code = $res['out_code'];
                }

                if ($code == '0') {
                    $conn->commit();

                    //Jika cash atau transfer
                    $tmp = ($caraBayar == 1 || $caraBayar == 3) ? ", silahkan lakukan konfirmasi pembayaran setelah anda membayar" : "";

                    return $this->redirect()->toUrl('buysn?msg='.$msg.$tmp);

                } else {
                    $conn->rollback();
                    $view->setVariable('errmsg', $msg);
                }
                
            }


            
            $confStorage = new \MLM\Model\Sysconfig\Storage($db);
            $getSNPrice = $confStorage->getConfigByName('SN_PRICE');
            while ($getSNPrice->next()) {
                $res = $getSNPrice->current();
                $snPrice = $res["int_value"];
            }
            $view->setVariable('snPrice', $snPrice);

            $accStorage = new \MLM\Model\Member\Account\Storage($db);
            $accountsPT = $accStorage->getAccountBank(100);

            $getBalance = $accStorage->getTotalBalance($identity->member_code);
            while ($getBalance->next()) {
                $res = $getBalance->current();
                $balance = $res["amount"];
            }

            $getParams = $this->getRequest()->getQuery();
            $msg = (isset($getParams["msg"])) ? $getParams["msg"] : "";

            $view->setVariable('accountsPT', $accountsPT);
            $view->setVariable('balance', $balance);
            $view->setVariable('msg', $msg);

            //Get Messages Notif
            $this->getMsgNotif($identity->member_type_id, $identity->member_id);
            return $view;
     }



     

     public function buyproductAction() {
            $identity = $this->hasSession();
            $this->layout('layout/member');

            $view = new ViewModel();
            $script = $this->getServiceLocator()->get('viewhelpermanager')
                    ->get('inlineScript');
            $script->appendScript("
                jQuery(function($) {

                    $('[data-rel=tooltip]').tooltip();

                    $('.select').css('width','150px').select2({allowClear:true})
                    .on('change', function(){
                            $(this).closest('form').validate().element($(this));
                    });


                    var validation = false;
                    $('#fuelux-wizard').ace_wizard().on('change' , function(e, info){
                            /*if(info.step == 1 && validation) {
                                    if(!$('#validation-form').valid()) return false;
                            }*/

                            if(info.step == 1) {
                                return cekProduct();
                            }
                            else if(info.step == 2) {
                                return konfirmasiPembelian();
                            }
                    }).on('finished', function(e) {
                            finishWizard();
                            /*
                            bootbox.dialog('Thank you! Your information was successfully saved!', [{
                                    'label' : 'OK',
                                    'class' : 'btn-small btn-primary',
                                    }]
                            );
                            */
                    }).on('stepclick', function(e){

                            //return false;//prevent clicking on steps

                    });


                    //documentation : http://docs.jquery.com/Plugins/Validation/validate


                    $('.chosen-select').chosen();

                    $('#modal-form').on('shown.bs.modal', function() {
                        $(this).find('.chosen-container').each(function() {
                            $(this).find('a:first-child').css('width', '210px');
                            $(this).find('.chosen-drop').css('width', '210px');
                            $(this).find('.chosen-search input').css('width', '200px');
                        });
                    });


                    $('#accordion-style').on('click', function(ev){
                            var target = $('input', ev.target);
                            var which = parseInt(target.val());
                            if(which == 2) $('#accordion').addClass('accordion-style2');
                             else $('#accordion').removeClass('accordion-style2');
                    });

             });

             $('#qty').ace_spinner({value:0,min:1,max:9999999,step:10, btn_up_class:'btn-info' , btn_down_class:'btn-info'})
                .on('change', function(){
                    return cekStok(this.value);
                        //alert(this.value)
                });

            ");

            $request = $this->getRequest();
            $getParams = $request->getQuery();
            if(isset($getParams['type'])){
                    $type = $getParams['type'];
            }

            $db = $this->_db;
            $conn = $db->getDriver()->getConnection();
            
            $type = $getParams["type"];
            $this->layout()->type = $type;
            $view->setVariable('type', $type);


            if ($request->isPost()) {
                $conn->beginTransaction();
                $post = $request->getPost();

                /*
                echo "<pre>";
                print_r($post);
		die();
		*/
		
                $dataPembelian = $post["dataPembelian"];
                $caraBayar = $post["rdPembayaran"];
                $totalHarga = $post["totalHarga"];
                $totalQty = $post["totalQty"];
                $memberType = ($post["type"] == 3) ? "AGENT" : "MEMBER";

                //echo "<pre>";
                $dataJson = base64_decode($dataPembelian);
               // echo $dataJson;
               // echo "<br>";
                $dataArray = json_decode($dataJson, true);
               // print_r($dataArray);
               // die();
                
                $memberId = $identity->member_id;
                $memberCode = $identity->member_code;
                
                $transStorage = new \MLM\Model\Transaction\Storage($db);
                $stockStorage = new \MLM\Model\Product\Stock\Storage($db);
                $accStorage = new \MLM\Model\Member\Account\Storage($db);
                $sysStorage = new \MLM\Model\Sysconfig\Storage($db);
                
                //Cek saldo 
                $saldo = 0;
                $getSaldo = $accStorage->getTotalBalance($memberCode);
                while($getSaldo->next()){
                                $resSaldo = $getSaldo->current();
                                $saldo = $resSaldo["amount"];
                        }
                        
                $minSaldo = 0;        
                $getMinSaldo = $sysStorage->getConfigByName("MIN_BALANCE");
                while($getMinSaldo->next()){
                                $resMinS = $getMinSaldo->current();
                                $minSaldo = $resMinS["int_value"];
                        }
                
                if (($saldo-$totalHarga) <  $minSaldo){
                	
                        $view->setVariable('errmsg', 'Saldo/Poin Anda tidak mencukupi');
                        return $view;
                        break;
                    
                }
		
	
		
                /*
                if($type == 2){
                        $memberId = $identity->member_id;
                }else if ($type == 3){
                        $memberId = $identity->member_reff_id;
                }
                 * 
                 */

                


                $transStorage = new \MLM\Model\Transaction\Storage($db);
                

                

                foreach ($dataArray as $key => $row) {
                    $agent[$key]  = $row['agentId'];
                }

                array_multisort($agent, SORT_ASC, $dataArray);
                
                //Insert Transaksi
                $agenId = 0;
                for ($x = 0; $x < count($dataArray); $x++){


                    //Insert TH
                    if ($agenId != $dataArray[$x]["agentId"]){
                        
                        $seq = 2;
                        $totalAmount = 0;
                        $totalQty = 0;
                        $agenId = $dataArray[$x]["agentId"];

                        
                        $accAgent = $accStorage->getAccountDetail($agenId);
                        while($accAgent->next()){
                            $res = $accAgent->current();
                            $accNumAgent = $res["account_num"];

                        }
                        
                        $trans = $transStorage->buyProduct($memberId, $memberCode, $accNumAgent, $totalQty, $totalHarga, $caraBayar, $memberType);
                        while($trans->next()){
                                $res = $trans->current();
                                $thId = $res["th_id"];
                                $thId2 = $res["th_id2"];
                                $msg = $res["out_msg"];
                                $code = $res['out_code'];
                        }

                        if ($code == '1') {
                            $conn->rollback();
                            $view->setVariable('errmsg', 'Pembelian Produk gagal, hubungi Admin');
                            return $view;
                            break;
                        }

                    }


                    //Insert TD
                    $amount = $dataArray[$x]["price"]*$dataArray[$x]["qty"];
                    $qty = $dataArray[$x]["qty"];

                    $dataTD = array(
                        "trans_header_id" => $thId,
                        "account_num1"    => $memberCode,
                        "account_num2"    => $accNumAgent,
                        "msisdn"          => $msisdn,
                        "amount1"         => $amount,
                        "xs1"             => $dataArray[$x]["suplierId"],
                        "xs2"             => $dataArray[$x]["prodname"],
                        "xs3"             => $caraBayar,
                        "xn1"             => $dataArray[$x]["prodid"],
                        "xn2"             => $qty,
                        "xn3"             => $dataArray[$x]["agentId"],
                        "mutation_type"   => 'T',
                        "notes_txt"       => 'Detail Pembelian Produk',
                        "seq"             => $seq
                    );

                    $insertTD = $transStorage->insertDataTrans("trans_detail", $dataTD);

                    if(!$insertTD){
                        $conn->rollback();
                        $view->setVariable('errmsg', 'Pembelian Produk gagal, hubungi Admin');
                        return $view;
                        break;
                    }

                    //Kurangi stok produk
                    $productId = $stockStorage->updateStock($dataArray[$x]["prodid"], $dataArray[$x]["agentId"], '-', $dataArray[$x]["qty"]);

                    if(!$productId){
                        $conn->rollback();
                        $view->setVariable('errmsg', 'Pembelian Produk gagal, hubungi Admin');
                        return $view;
                        break;
                    }


                    $totalAmount = $totalAmount + $amount;
                    $totalQty = $totalQty + $qty;


                    $dataUp = array("amount1" => $totalAmount, "xn2" => $totalQty, "xn3" => $agenId);
                    $where = array("trans_header_id" => $thId2, "account_num1" => $accNumAgent, "seq" => 1);
                    $transStorage->updateTD($dataUp, $where);

                    $dataUp2 = array("amount1" => $totalAmount, "xn2" => $totalQty, "xn3" => $agenId);
                    $where2 = array("trans_header_id" => $thId, "account_num2" => $accNumAgent, "seq" => 1);
                    $transStorage->updateTD($dataUp2, $where2);


                    $seq++;

                }

                $conn->commit();

                //Jika cash atau transfer
                $tmp = ($caraBayar == 1 || $caraBayar == 3) ? ", silahkan lakukan konfirmasi pembayaran setelah anda membayar" : "";

                return $this->redirect()->toUrl('buyproduct?msg=Pembelian Produk Sukses'.$tmp);
                
            }


            //$getParams = $this->getRequest()->getQuery();
            $msg = (isset($getParams["msg"])) ? $getParams["msg"] : "";
            

            $storage = new \MLM\Model\Agent\Storage($db);
            $configstorage = new \MLM\Model\Sysconfig\Storage($db);

            $supliers = $storage->getSuplierList();
            $agents = $storage->getAgentList($identity->member_reff_id, $type);
            $getMinOrder = $configstorage->getConfigByName('MIN_ORDER_AGENT');
            while ($getMinOrder->next()) {
                $resMO = $getMinOrder->current();
                $minOrder = $resMO["int_value"];
            }

            $view->setVariable('supliers', $supliers);
            $view->setVariable('agents', $agents);
            $view->setVariable('isAgent', $identity->member_reff_id);
            $view->setVariable('minOrder', $minOrder);

            $accStorage = new \MLM\Model\Member\Account\Storage($db);
            $accountsPT = $accStorage->getAccountBank(100);

            $getBalance = $accStorage->getTotalBalance($identity->member_code);
            while ($getBalance->next()) {
                $res = $getBalance->current();
                $balance = $res["amount"];
            }
				
		 
            $view->setVariable('accountsPT', $accountsPT);
            $view->setVariable('balance', $balance);
            $view->setVariable('msg', $msg);
            

            //Get Messages Notif
            $this->getMsgNotif($identity->member_type_id, $identity->member_id);
            return $view;
     }


    public function confirmlistAction(){
        $identity = $this->hasSession();
        $this->layout('layout/member');
        $view = new ViewModel();

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        return $view;
    }

    public function payconfirmAction(){
        $identity = $this->hasSession();
        $this->layout('layout/member');
        $view = new ViewModel();

        $getParams = $this->getRequest()->getQuery();
        $transId = $getParams["transId"];
        $msg = (isset($getParams["msg"])) ? $getParams["msg"] : "";

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();

        $request = $this->getRequest();
        if ($request->isPost()) {
            $conn->beginTransaction();
            $post = $request->getPost();

            $transId = $post["transId"];
            $tglBayar = $post["tglBayar"];
            $caraBayar = $post["caraBayar"];
            $rekAsal = $post["rekAsal"];
            $rekTujuan = $post["rekTujuan"];
            $jmlTransfer = $post["jmlTransfer"];
            $ket = $post["ket"];

            $agentStorage = new \MLM\Model\Agent\Storage($db);

            /*
            $dataTrans = array(
                'trans_header_id' => $transId,
                'pay_method' => $caraBayar,
                'from_account_id' => $rekAsal,
                'to_account_id' => $rekTujuan,
                'transfer_amount' => $jmlTransfer,
                'notes' => $ket
            );
             *
             */

            $dataTrans = array(
                $transId,
                $tglBayar,
                $caraBayar,
                $rekAsal,
                $rekTujuan,
                $jmlTransfer,
                $ket
            );


            $paymentId = $agentStorage->savePaymentConfirm($dataTrans);

            if(!$paymentId){
                $conn->rollback();
                $view->setVariable('errmsg', 'Konfirmasi Pembayaran Gagal, hubungi Admin');
                return $view;
            }

            $data = array(
                'trans_status'  => 'PAY_CONFIRM'
            );
            $where = array('trans_header_id' => $transId);
            $res = $agentStorage->updateTransStatus($data, $where);

            $conn->commit();

            return $this->redirect()->toUrl('payconfirm?msg=Konfirmasi Pembayaran Sukses, menunggu verifikasi Admin');


            die();
        }

        $transStorage = new \MLM\Model\Transaction\Storage($db);
        $transDetail = $transStorage->getPriceTransDetail($transId);

        while ($transDetail->next()) {
            $res = $transDetail->current();
            $transCode = $res["trans_code"];
            $totalTrans = $res["amount1"];
        }

        $accStorage = new \MLM\Model\Member\Account\Storage($db);
        $getAccMember = $accStorage->getAccountBank($identity->member_id);
        $getAccPT = $accStorage->getAccountBank(100);

        $view->setVariable('transId', $transId);
        $view->setVariable('transCode', $transCode);
        $view->setVariable('totalTrans', $totalTrans);
        $view->setVariable('msg', $msg);
        $view->setVariable('getAccMember', $getAccMember);
        $view->setVariable('getAccPT', $getAccPT);

        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
        $script->appendScript("
          jQuery(function($) {
            $('.chosen-select').chosen();

            $('#modal-form').on('shown.bs.modal', function() {
                $(this).find('.chosen-container').each(function() {
                    $(this).find('a:first-child').css('width', '210px');
                    $(this).find('.chosen-drop').css('width', '210px');
                    $(this).find('.chosen-search input').css('width', '200px');
                });
            })

            $('.date-picker').datepicker({autoclose:true}).next().on(ace.click_event, function(){
                            $(this).prev().focus();
                    });
        })
        ");

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        return $view;
    }


    public function stockAction() {
        $identity = $this->hasSession();

        $this->layout('layout/member');
        $view = new ViewModel();

        /*
        if ($identity->member_id == 100 || $identity->member_reff_id == "")
            $memberId = $identity->member_id;
        else $memberId = $identity->member_reff_id;
         * 
         */

        $memberId = $identity->member_id;

        $view->setVariable('memberId', $memberId);
        
        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        return $view;
    }


    public function agentlistAction()
    {

        $identity = $this->hasSession();
        $this->layout('layout/admin');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        $view = new ViewModel();

        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
                $script->appendScript("
                  jQuery(function($) {
                    $('.chosen-select').chosen();

                    $('#modal-form').on('shown.bs.modal', function() {
                        $(this).find('.chosen-container').each(function() {
                            $(this).find('a:first-child').css('width', '210px');
                            $(this).find('.chosen-drop').css('width', '210px');
                            $(this).find('.chosen-search input').css('width', '200px');
                        });
                    });

                })
                ");

        $storage = new \MLM\Model\Product\Storage($this->_db);
        $supliers = $storage->listSuplier();
        $view->setVariable('supliers', $supliers);

        return $view;

    }


    public function snAction()
    {
        $identity = $this->hasSession();
        $this->layout('layout/member');
        $view = new ViewModel();
        $view->setVariable('memberId', $identity->member_id);

        $getParams = $this->getRequest()->getQuery();
        $type = $getParams["type"];
        $view->setVariable('type', $type);

        $this->layout()->type = $type;

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        $request = $this->getRequest();

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();

        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
        $script->appendScript("
          jQuery(function($) {
            $('.chosen-select').chosen();

            $('#modal-form').on('shown.bs.modal', function() {
                $(this).find('.chosen-container').each(function() {
                    $(this).find('a:first-child').css('width', '210px');
                    $(this).find('.chosen-drop').css('width', '210px');
                    $(this).find('.chosen-search input').css('width', '200px');
                });
            })
        })
        ");

        if ($request->isPost()) {
            $conn->beginTransaction();
            $formData = $request->getPost();

            $sn   = $formData['sn'];
            $snList   = $formData['snList'];
            $flag   = $formData['flag'];

            $err = 0;
            $errorMsg = "";

            /*
             * Check List
             */
            if ($snList == "" && $flag == 1){
                $errorMsg .= "* SN harus dipilih.<br>";
                //return;
                $err = 1;
            }


            $msg = "";
            if ($err == 0){

                    if ($flag == 1){ //Aktifkan yang dipilih
                        $msg = "Diaktifkan";
                    }else if ($flag == 2){ //Aktifkan semua
                        $msg = "Diaktifkan Semua";
                    }else if ($flag == 3){  //Pasifkan semua
                        $msg = "Dipasifkan Semua";
                    }

                    $storage = new \MLM\Model\Sn\Storage($db);
                    $res = $storage->aktivasiSN($snList, $flag, $sn);

                    if(!$res){
                        $conn->rollback();
                        $view->setVariable('msg', 'SN Gagal '.$msg);
                        return $view;
                    }

                    $conn->commit();
                    $view->setVariable('msg', 'SN Berhasil '.$msg);
                    return $view;

            }else{

                $view->setVariable('errmsg', $errorMsg);
                return $view;
            }



        }else{            
            return $view;
        }




    }


     //Get Messages Notif
    private function getMsgNotif($memberTypeId, $memberId){


        $identity = $this->hasSession();

        /*
        if ($memberId == 100) $memberId2 = $memberId;
        else{

            //$memberId2 = ($identity->member_reff_id == "") ? $memberId : $identity->member_reff_id;
            $memberId2 = $memberId;
            $isAgent = $identity->member_reff_id;
        }
         *
         */

        $isAgent = $identity->member_reff_id;
        $memberCode = $identity->member_code;


        $notifStorage = new \MLM\Model\Notification\Storage($this->_db);
        $notifMsg = new \MLM\Model\Notification($notifStorage);
        $newMsgCnt = $notifMsg->getCountNewMsg($memberId);
        $newMsgList = $notifMsg->getNewMsgList($memberId);

        $newAlertCnt = $notifMsg->getCountAlertApproval($memberTypeId, $memberId, $isAgent, $memberCode);
        $newAlertList = $notifMsg->getAlertApproval($memberTypeId, $memberId, $isAgent, $memberCode);

        $action = $this->getEvent()->getRouteMatch()->getParam('action');
        $control = $this->getEvent()->getRouteMatch()->getParam('controller');

        $this->layout()->menu = $control.'\\'.$action;
        $this->layout()->newMsgCnt = $newMsgCnt;
        $this->layout()->newMsgList = $newMsgList;
        $this->layout()->newAlertCnt = $newAlertCnt;
        $this->layout()->newAlertList = $newAlertList;

    }

     private function hasSession() {
            $auth = new AuthenticationService();

            $identity = $auth->getIdentity();
            //print_r($identity);
            if (!$auth->hasIdentity()) {
                    //echo "gak ada session";
                    return $this->redirect()->toRoute('application/default', array('controller' => 'Index', 'action' => 'login'));
            } else {
                    return $auth->getIdentity();
            }
    }

}
?>
